package com.metadata_system.common.service;


import com.metadata_system.common.http.request_dto.UserLoginRequest;
import com.metadata_system.common.http.response_dto.TokenResponse;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.exception.ApiException;
import com.metadata_system.common.db.entity.AuthReflushToken;
import com.metadata_system.common.db.entity.AuthToken;
import com.metadata_system.common.db.mapper.AuthReflushTokenMapper;
import com.metadata_system.common.db.mapper.AuthTokenMapper;
import com.metadata_system.common.dto.JwtToken;


import com.metadata_system.common.utils.DateTimeUtil;
import com.metadata_system.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author safi
 * @date 2019年10月9日20:30:57
 */
@Service
@Slf4j
public class AuthTokenService {
    private int tokenExpireSeconds = 1296000;
    private int reflushTokenExpireSeconds = 1296000 * 2;

    @Autowired(required = false)
    AuthTokenMapper authTokenMapper;
    @Autowired(required = false)
    AuthReflushTokenMapper authReflushTokenMapper;
    @Autowired
    AuthReflushTokenService authReflushTokenService;
    @Autowired
    UserService userService;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    AuthTokenRepo authTokenRepo;


    // 生成token
    public TokenResponse generate(UserLoginRequest userLoginRequest) {
        if (userLoginRequest.getParams()==null){
            userLoginRequest.setParams("0");
        }
        String token = UUID.randomUUID().toString();
        String reflushToken = UUID.randomUUID().toString();
        Date currDate = new Date();
        // 插入: token
        this.authTokenRepo.insert(AuthToken.builder()
                .createdAt(currDate)
                .userId(userLoginRequest.getUserId())
                .deviceId(userLoginRequest.getDeviceId())
                .platform(userLoginRequest.getPlatform())
                .username(userLoginRequest.getUsername())
                .tokenId(token)
                .reflushTokenId(reflushToken)
                .status(true)
                .expiredTime(DateTimeUtil.addSeconds(currDate, this.tokenExpireSeconds))
                .build());

        // 插入: reflushToken
        this.authReflushTokenMapper.insert(AuthReflushToken.builder()
                .expiredTime(DateTimeUtil.addSeconds(currDate, this.reflushTokenExpireSeconds))
                .tokenId(token)
                .reflushTokenId(reflushToken)
                .createdTime(currDate)
                .status(true)
                .build());
        ApiResult result = this.userService.getUidByUsername(userLoginRequest.getUsername());
        if (result.getCode() > 0) {
            throw new ApiException("用户信息 不存在");
        }
        String id = String.valueOf(result.getData());

//        log.info("userLoginRequest: "+userLoginRequest.toString());
        // 构造: JwtToken-map
        String jwtToken = jwtUtil.generateToken(JwtToken.builder()
                    .tokenId(token)
                    .username(userLoginRequest.getUsername())
                    .role(userLoginRequest.getRole())
                    .params(Integer.valueOf(userLoginRequest.getParams()!=null?userLoginRequest.getParams():"0"))
                    .build()
                    .encodeID(id)
                    .backMap()
        );
        // 构造: ReflushToken-map
        String reflushJwtToken = jwtUtil.generateToken(JwtToken.builder()
                .tokenId(reflushToken)
                .username(userLoginRequest.getUsername())
                .role(userLoginRequest.getRole())
                .params(Integer.valueOf(userLoginRequest.getParams()!=null?userLoginRequest.getParams():"0"))
                .build()
                .encodeID(id)
                .backMap()
        );


        // 返回: jwtToken
        return TokenResponse.builder()
                .expireTime(this.tokenExpireSeconds)
                .token(jwtToken)
                .reflushToken(reflushJwtToken)
                .role(userLoginRequest.getRole())
                .build();
    }


}
